package org.easyframework.frm.session;

import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

import org.easyframework.frm.cfg.Configuration;
import org.easyframework.frm.cfg.Settings;
import org.easyframework.frm.exception.FRMException;

/**
 * <code>SessionFactoryImpl</code> is the implementation of
 * <code>SessionFactory</code>
 * 
 * @author Amila Domingo
 * @since 1.0
 */
public class SessionFactoryImpl implements SessionFactory {

	private final Map<String, Configuration> configuration = new HashMap<String, Configuration>();

	private Settings settings;

	private String configFileName = "frm-configuration.xml";

	/**
	 * Constructs the session factory
	 */
	public SessionFactoryImpl() {

		buildSesstionSettings();

	}

	public void buildSesstionSettings() {

		ClassLoader classLoader = Thread.currentThread().getContextClassLoader();

		InputStream rsrc = classLoader.getResourceAsStream(configFileName);

		if (rsrc == null) {
			
			throw new FRMException("Can not find a resource file with name " + configFileName);
		}
		
		try {

			
			
		} catch (Exception me) {
			
			
		}

	}

	public Session openSession() throws FRMException {

		return new SessionImpl(getConnection(), this);

	}

	private Connection getConnection() {

		try {

			Class.forName(settings.getDriverClass());

			return DriverManager.getConnection(settings.getUrl(), settings.getUsername(), settings.getPassword());

		} catch (ClassNotFoundException e) {

			throw new FRMException("Invalid driver class or driver class not found", e);

		} catch (SQLException e) {

			throw new FRMException(e.getMessage(), e);

		}
	}

	public Configuration getConfiguration(String template) {

		return configuration.get(template);

	}

	public Settings getSettings() {

		return settings;

	}

	/**
	 * Adds a resource to the session factory
	 */
	public void addResource(String resource) {

		configuration.put(resource, Configuration.configure());

	}

	public void setConfigFileName(String configFileName) {
		this.configFileName = configFileName;
	}

}
